from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from rest_framework import mixins
from rest_framework import viewsets
from django.contrib.auth import get_user_model
from users.serializers import UserRegSerializer, UserDetailSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from rest_framework import authentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
# from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

User = get_user_model()
class CustomBackend(ModelBackend):
    """自定义用户验证"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        print('Authentication123123123123123123123123123123123123123123123123123123')
        print(username)
        try:
            user = User.objects.get(Q(username=username)|Q(mobile=username))
            print(user)
            if user.check_password(password):
                return user
        except Exception as e:
            print('000000000000000000')
            print(e)
            return None

class UserViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    用户
    """
    serializer_class = UserRegSerializer
    queryset = User.objects.all()
    authentication_classes = []
    permission_classes = []
    # authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication )

    def get_serializer_class(self):
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer

        return UserDetailSerializer

    # permission_classes = (permissions.IsAuthenticated, )
    def get_permissions(self):
        print('self.action')
        print(self.action)
        if self.action == "retrieve":
            return [permissions.IsAuthenticated()]
        elif self.action == "create":
            print('Creating  get_permissions')
            return []

        return []

    def create(self, request, *args, **kwargs):
        print('create12120000000')
        serializer = self.get_serializer(data=request.data)
        print(request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        re_dict = serializer.data
        print('created123123123123123123123123123123123123123123123123')
        print(re_dict)
        # payload = jwt_payload_handler(user)
        # re_dict["token"] = jwt_encode_handler(payload)
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        print(token)
        re_dict["token"] = token
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def get_object(self):
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()